<template>
  <el-dialog :visible.sync="visible" :title="props.isEditing ? '修改用户信息' : '新建用户'" @close="cancel" width="400px">
    <el-form :model="formData" :rules="rules" ref="form" label-width="80px">
      <el-form-item prop="username" label="用户名">
        <el-input v-model="formData.username" style="width: 100%; text-align: left;" :disabled="props.isEditing"></el-input>
      </el-form-item>
      <el-form-item prop="password_old" label="旧密码" v-if="props.isEditing">
        <el-input type="password" v-model="formData.password_old" style="width: 100%; text-align: left;"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input type="password" v-model="formData.password" style="width: 100%; text-align: left;"></el-input>
      </el-form-item>
      <el-form-item prop="password2" label="密码2">
        <el-input type="password" v-model="formData.password2" style="width: 100%; text-align: left;"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="手机号">
        <el-input v-model="formData.mobile" style="width: 100%; text-align: left;"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="电子邮件">
        <el-input v-model="formData.email" style="width: 100%; text-align: left;"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-radio-group v-model="formData.role" :disabled="props.isEditing">
          <el-radio v-for="group, index in groups" :label="group.id" :key="'group'+index">{{ group.name }}</el-radio>
          <!-- <el-radio label="管理员">管理员</el-radio>
          <el-radio label="研究员">研究员</el-radio>
          <el-radio label="学生">学生</el-radio> -->
        </el-radio-group>
      </el-form-item>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveUser">{{props.isEditing ? '更新' : '创建'}}</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { loadGroups, addUser, myUserInfo, updateUserInfo, resetMyUserInfo } from '../utils/apiUser'
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus'
const visible = ref(false)
const formData = reactive({
  username: '',
  mobile: '',
  email: '',
  password: '',
  password2: '',
  role: '',
  password_old: ''  // For edit
})

const groups = ref([])

const props = defineProps({
  isEditing: {
    type: Boolean,
    required: true
  }
})

const clearFormData = () => {
  formData.username = ''
  formData.mobile = ''
  formData.email = ''
  formData.password = ''
  formData.password2 = ''
  formData.role = ''
}

const setMyUserInfo = () => {
  const ui = myUserInfo()
  formData.username = ui.username
  formData.mobile = ui.mobile
  formData.email = ui.email
  formData.role = ui.groups[0].id
}

watch([()=>props.isEditing], ()=>{
  clearFormData()
  if (props.isEditing) {
    setMyUserInfo()
  }
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入11位手机号', trigger: ['blur', 'change'] },
    { validator: (rule, value, callback) => {
        if (/^1\d{10}$/.test(formData.mobile)) {
          callback()
        } else {
          callback(new Error('手机号必须是1开头的11位数字'))
        }
      }, trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的电子邮件地址', trigger: ['blur', 'change'] }
  ],
  password_old: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        console.log('password2', value, formData.password)
        if (value !== formData.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ]
}

const form = ref(null)

onMounted(()=>{
  console.log('form', form.value)
  loadGroups().then(res=>{
    groups.value = res.data
    formData.role = groups.value[0].id
    // res.data.forEach(v=>(groups.value[v.name]=v.id))
  })
})

const createUser = () => {
  const createData = {
    username: formData.username,
    password: formData.password,
    mobile: formData.mobile,
    email: formData.email,
    groups: [parseInt(formData.role)]
  }
  // 调用创建用户的函数
  const result = addUser(createData).then(res=>{
    visible.value = false
    if (res.code === 0) {
      emits('createuser-success', result.message)
      ElMessage.success('新建用户成功')
    } else {
      ElMessage.error('新建用户失败')
    }
  }).catch(error=>{
    // 显示错误信息，不关闭对话框
    ElMessage.error('新建用户失败')
  })
}

const editUser = () => {
  const updateData = {
    password_old: formData.password_old,
    password: formData.password,
    mobile: formData.mobile,
    email: formData.email,
  }
  // 调用创建用户的函数
  const result = updateUserInfo(myUserInfo().id, updateData).then(res=>{
    visible.value = false
    if (res.code === 0) {
      resetMyUserInfo(res.data)
      emits('createuser-success', result.message)
      ElMessage.success('更新用户信息成功')
    } else {
      ElMessage.error('更新用户信息失败')
    }
  }).catch(error=>{
    // 显示错误信息，不关闭对话框
    ElMessage.error('更新用户信息失败')
  })
}

const saveUser = () => {
  console.log('form', form.value)
  form.value.validate((valid) => {
    if (valid) {
      if (props.isEditing) {
        editUser()
      } else {
        createUser()
      }
    } else {
      // 显示错误信息，不关闭对话框
      ElMessage.error('请填写正确的信息')
    }
  })
}

const cancel = () => {
  visible.value = false
  emits('createuser-canceled')
}
const emits = defineEmits(['createuser-canceled', 'createuser-success'])
</script>
<style scoped>
/* 样式可以根据需要自行调整 */
</style>
